import { EventSourcePolyfill } from "event-source-polyfill";
import { useAuthStore } from "@/store";
import { API_BASE_URL } from "@/constant/env";

const STREAM_COMPLETE = "SZGD_CHAT_END";
const STREAM_ERROR = "CONNECTION_ERROR";

export async function requestStream(
  conversationId: string,
  message: string,
  events: {
    message: (message: string, done: boolean) => void;
    error: (error: Error) => void;
  },
) {
  const authStore = useAuthStore.getState();
  const url = `${API_BASE_URL}/openai/chatFlow/${authStore.user.id}/${conversationId}?questions=${encodeURIComponent(message)}`;
  const headers: HeadersInit = {
    "Content-Type": "application/json",
  };
  if (authStore.token) {
    headers.Authorization = `${authStore.token}`;
  }
  let generating: boolean = true;
  let responseText: string = "";
  const decoder = new TextDecoder();
  let sse = new EventSourcePolyfill(url, {
    headers,
  });
  const done = (): void => {
    sse.close();
    generating = false;
    events.message(responseText, true);
  };
  sse.addEventListener("open", function () {
    console.log("open");
    generating = true;
  });

  sse.addEventListener("message", function (res) {
    try {
      const content = JSON.parse(res.data);
      const text = content.str;
      if (text === STREAM_COMPLETE) {
        return done();
      } else if (text === STREAM_ERROR) {
        return events.error(new Error("Stream Error"));
      }
      responseText += text;
      events.message(responseText, false);
    } catch (error) {
      events.error(new Error("Stream Error"));
    }
  });
  sse.addEventListener("error", function (error: any) {
    done();
    events.error(new Error("Stream Error"));
  });
}
